<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>员工管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-input placeholder="请输入内容" v-model="querInfo.name"class="input-with-select" clearable>                    
                    <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                </el-input></el-col>
                    <el-col :span="4">
                    <el-button type="primary" @click="addDialog=true">添加用户</el-button>
                    </el-col>
                </el-row>
                <!--用户列表的渲染-->
                <el-table :data="userlist" border stripe >
                    <el-table-column type="index"></el-table-column>
                    <el-table-column label="头像" >
                        <template slot-scope="scope">
                            <el-image :src="scope.row.avatarImg" style="height: 70px;height: 50px;"></el-image>
                        </template>   
                    </el-table-column>
                    <el-table-column label="姓名" prop="name"></el-table-column>
                    <el-table-column label="电话" prop="phone"></el-table-column>
                    <el-table-column label="角色" prop="roles[0].roleName"></el-table-column>
                    <el-table-column label="状态" prop="status">
                            <template slot-scope="scope">
                                <el-switch
                                    v-model="scope.row.status"
                                    active-value="0"
                                    inactive-value="1"
                                    active-color="#13ce66"
                                    inactive-color="#ff4949"
                                    @change="changeuserstatus(scope.row)"
                                >
                                </el-switch>
                                <span>{{ scope.row.status === "0" ? '启用' : '停用' }}</span>
                            </template>
                        </el-table-column>
                            <!--用户列表操作列-->
                    <el-table-column label="操作" >
                        <template slot-scope="scope">
                            <el-tooltip class="item" effect="dark" content="编辑用户" placement="top">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showUpdateDialog(scope.row.id)"></el-button>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" content="删除角色" placement="top">
                                <el-button type="danger" icon="el-icon-delete"size="mini" @click="removeUserById(scope.row.id)"></el-button>
                            </el-tooltip>
                            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
                                <el-button type="warning" icon="el-icon-setting"size="mini"></el-button>
                            </el-tooltip>                            
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[2, 5, 10, 15]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
        </el-card>

        <!--添加用户对话框-->
        <el-dialog
        title="添加用户"
        :visible.sync="addDialog"
        width="50%"
        @close="addDialogClose"
        >
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"
         label-width="70px" >
            <el-form-item label="用户名" prop="name">
                <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="登录账号" prop="loginName">
                <el-input v-model="addForm.loginName"></el-input>
            </el-form-item> 
            <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="addForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="用户头像">
                <el-upload
            name="photo"
            class="avatar-uploader"
            action="http://localhost:8989/buy/sysUser/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 100px;height: 80px;">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialog = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
        </el-dialog>
        <!--编辑用户信息对话框-->
        <el-dialog title="编辑用户"  :visible.sync="updatedialogVisible" width="50%">
            <el-form :model="updateForm" :rules="updaterules" ref="updateFormRef"
             label-width="70px" >
                <el-form-item label="用户名" prop="name">
                    <el-input v-model="updateForm.name"disabled></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="updateForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="updateForm.password"></el-input>
                </el-form-item>
                <el-form-item label="登陆账号" prop="loginName">
                    <el-input v-model="updateForm.loginName"></el-input>
                </el-form-item>
            </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="updatedialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="updateUserInfo(updateForm.id)">确 定</el-button>
  </div>
</el-dialog>
    </div>
</template>
<script>
export default{
    data(){
        return{
            //查询到的修改对象
            updateForm:{},
            //修改用户的校验规则
            updaterules:{
                name:[
                    {required:true,message:'请输入用户名',trigger:'blur'},
                    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                loginName:[
                    {required:true,message:'请输入登陆账号',trigger:'blur'},
                    {min: 5, max:15 , message: '长度在 5 到 15 个字符', trigger: 'blur' }
                ],
                phone:[
                    {required:true,message:'请输入手机号',trigger:'blur'},
                    {min: 11, max: 11, message: '手机号长度应该为11位', trigger: 'blur' }
                ],
                password:[
                    {required:true,message:'请输入密码',trigger:'blur'},
                    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ]
            },
            imageUrl: '',
            //查询条件参数
            querInfo:{
                name:'',
                locked:null
            },
            //分页的三个参数
            currentPage :1,
            pageSize:5,
            total:0,
            //用户列表
            userlist:[],
            value1:true,
            //添加的对话框展示属性
            addDialog:false,
            //修改的对话框展示属性
            updatedialogVisible:false,
            //添加用户的对象
            addForm:{
               loginName:'',
               name:'',
               phone:'',
               password:'',
               avatarImg:''
            },//添加用户的验证参数
            addFormRules:{
                name:[
                    {required:true,message:'请输入用户名',trigger:'blur'},
                    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                loginName:[
                    {required:true,message:'请输入登陆账号',trigger:'blur'},
                    {min: 6, max:15 , message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                phone:[
                    {required:true,message:'请输入手机号',trigger:'blur'},
                    {min: 11, max: 11, message: '手机号长度应该为11位', trigger: 'blur' }
                ],
                password:[
                    {required:true,message:'请输入密码',trigger:'blur'},
                    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    created(){
        this.getUserList()
    },
    
    methods:{
        //获取所有用户列表事件
       async getUserList(){   
        const {data:res}= await this.$http.post(`/sysUser/getAllUsers/${this.currentPage}/${this.pageSize}`,this.querInfo)
        this.userlist=res.list
        this.total=res.total
        console.log("的手法首发:",this.userlist)
        console.log("的手法首发:",this.total)
        },//用户状态改变事件
       async changeuserstatus(userinfo){
        const {data:res}=await this.$http.post('/sysUser/changeUserstatus',userinfo)
        console.log(res)
            if(res!==true){
                return this.$message.error("更新用户状态失败")
            }
            this.$message.success("停用或启用用户成功")
        },//页大小改变事件
        handleSizeChange(newSize){
            this.pageSize=newSize
            this.getUserList()
        },//页数改变事件
        handleCurrentChange(newPage){
            this.currentPage=newPage
            this.getUserList()
        },//表单退出重置
        addDialogClose(){
            this.$refs.addFormRef.resetFields()
        },//表单提交预验证
        addUser(){
            console.log(this.addForm)
            this.$refs.addFormRef.validate(async valid =>{
                if (valid) {
          const { data: res} = await this.$http.post('/sysUser/add', this.addForm)
          console.log('res', res)
          if(res === 'ok') {
            this.$message.success("新增后台用户成功")
            this.addDialog=false
            this.getUserList()
          }
        }else{
            return this.$message.error("请完成表单验证")
        }

            })
         },//头像预验证
         beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
            },//头像上传以及返回唯一路径
        handleAvatarSuccess(res, file) {
                console.log('res', res)
                console.log('file', file)
                this.imageUrl = res;
                this.addForm.avatarImg = this.imageUrl;
         },//展示修改对话框
            async showUpdateDialog(id){
            const {data:res}= await  this.$http.post(`/sysUser/getUserById/${id}`)
            this.updateForm=res
            console.log(this.updateForm)
            this.updatedialogVisible=true
        },//修改用户信息并提交
        updateUserInfo(id){
            this.$refs.updateFormRef.validate(async valid=>{
                if(!valid)return
             const {data:res} =await this.$http.post(`/sysUser/updateUserById`,this.updateForm)
             if(res){
                this.$message.success("修改用户信息成功")
                this.updatedialogVisible=false
                this.getUserList()
             }

            })
        },//根据id删除用户
        async removeUserById(id){
           //console.log(id)
            //弹框询问用户是否删除数据
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            //如果用户确认删除，则返回值为字符串 confirm
            //如果用户取消删除，则返回值为字符串 cancel
            //console.log(confirmResult)
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            
            const { data: res } = await this.$http.post(`/sysUser/deleteUser/${id}`)
            if (res!== true) {
                return this.$message.error('删除用户失败！')
            }
            this.$message.success('删除用户成功！')
            this.getUserList()
        }
       
    }
}
</script>
<style lang="less"scoped>

</style>